from django.http import HttpResponse, JsonResponse
from django.shortcuts import render
from django.contrib.auth.views import login_required
from .models import Collect
from main.models import Book


# Create your views here.
@login_required
def collect(request):
    cs = Collect.objects.filter(user=request.user)
    return render(request, "operate/collect.html", context={"cs": cs})


@login_required
def change_collect(request):
    if request.method == "POST":
        book_id = request.POST.get("book_id")
        book = Book.objects.get(id=book_id)
        c = Collect.objects.filter(user=request.user, book=book).first()
        if c:
            c.delete()
            return JsonResponse({
                'code': 0,
                'msg': "取消收藏成功",
                'data': {
                    'state': False
                }
            })
        else:
            temp = Collect()
            temp.user = request.user
            temp.book = book
            temp.save()
            return JsonResponse({
                'code': 0,
                'msg': "收藏成功",
                'data': {
                    'state': True
                }
            })
    else:
        return JsonResponse({
            'code': -1,
            'msg': "方法不允许"
        })
